package com.viewpagerindicator.sample.fragents;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.viewpagerindicator.sample.CutokApplication;
import com.viewpagerindicator.sample.R;
import com.viewpagerindicator.sample.adapters.GoodsListAdapter;
import com.viewpagerindicator.sample.beans.Goods;
import com.viewpagerindicator.sample.util.URLs;
import com.viewpagerindicator.sample.view.LoginDialog;
import com.viewpagerindicator.sample.view.RegisterDialog;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

public final class FifthFragment extends Fragment {
    private static final String KEY_CONTENT = "TestFragment:Content";

    public static FifthFragment newInstance(String content) {
        FifthFragment fragment = new FifthFragment();
        return fragment;
    }

    private String mContent = "???";
    ArrayList<Goods> goodsArrayList=new ArrayList<>();
    private ListView listView;
    private GoodsListAdapter adapter;
    private View unLoginBg;
    private View loginedBg;
    private View progressingBg;
    private View listviewBg;
    private View errormsgBg;
    Button registerButton;
    Button loginButton;
    Button logoutButton;
    TextView userLoginNameTextView;
    CutokApplication application;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if ((savedInstanceState != null) && savedInstanceState.containsKey(KEY_CONTENT)) {
            mContent = savedInstanceState.getString(KEY_CONTENT);
        }
        this.application= (CutokApplication) getActivity().getApplicationContext();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view= inflater.inflate(R.layout.fifth_layout,container,false);
        listView= (ListView) view.findViewById(R.id.first_layout_listview);
        unLoginBg=  view.findViewById(R.id.bg_unlogin);
        loginedBg=  view.findViewById(R.id.bg_logined);
        registerButton= (Button) view.findViewById(R.id.to_register);
        loginButton= (Button) view.findViewById(R.id.to_login);
        progressingBg=view.findViewById(R.id.progress_bg);
        errormsgBg=view.findViewById(R.id.errormsg_bg);
        listviewBg=view.findViewById(R.id.bg_list);
        userLoginNameTextView= (TextView) view.findViewById(R.id.user_login_name);
        logoutButton= (Button) view.findViewById(R.id.to_logout);
        adapter=new GoodsListAdapter(getActivity(),R.layout.goods_listview_item,goodsArrayList);
        listView.setAdapter(adapter);
        if(application.isLogined()){
            initData();
            loginedBg.setVisibility(View.VISIBLE);
            unLoginBg.setVisibility(View.GONE);
            userLoginNameTextView.setText(application.getUserLoginName());
        }else{
            loginedBg.setVisibility(View.GONE);
            unLoginBg.setVisibility(View.VISIBLE);
        }
        registerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final RegisterDialog loginDialog = new RegisterDialog(getActivity(), new RegisterDialog.LoginEventLinster() {
                    @Override
                    public void logineed(boolean isSuccess) {
                        if (isSuccess) {
                            //login success
                            initData();
                            userLoginNameTextView.setText(application.getUserLoginName());
                            unLoginBg.setVisibility(View.GONE);
                            loginedBg.setVisibility(View.VISIBLE);
                        }
                    }
                });
                loginDialog.show();
            }
        });
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LoginDialog loginDialog = new LoginDialog(getActivity(), new LoginDialog.LoginEventLinster() {
                    @Override
                    public void logineed(boolean isSuccess) {
                        if (isSuccess) {
                            //login success
                            initData();
                            unLoginBg.setVisibility(View.GONE);
                            loginedBg.setVisibility(View.VISIBLE);
                            userLoginNameTextView.setText(application.getUserLoginName());
                        }
                    }
                });
                loginDialog.show();
            }
        });
        logoutButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                application.logout();
                unLoginBg.setVisibility(View.VISIBLE);
                loginedBg.setVisibility(View.GONE);
                initData();
            }
        });
        return view;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString(KEY_CONTENT, mContent);
    }
    /**
     * 获取商品
     * */
    public void initData(){
        show(progressingBg);
        String sessionid=application.getSessionId();
        AsyncHttpClient client = new AsyncHttpClient();
        RequestParams requestParams=new RequestParams();
        requestParams.put("sessionid",sessionid);
        client.get(URLs.listgoodsbysessionid,requestParams, new AsyncHttpResponseHandler() {

            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                //解析数据
                try {
                    List<Goods> temp = Goods.parseList(responseBody);
                    if (temp != null&&temp.size()>0) {
                        goodsArrayList.clear();
                        goodsArrayList.addAll(temp);
                        adapter.notifyDataSetChanged();
                        show(listviewBg);
                    }else{
                        show(errormsgBg);
                    }
                } catch (Exception e) {
                    Toast.makeText(getActivity(), getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                    show(errormsgBg);
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                Toast.makeText(getActivity(), getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                show(errormsgBg);
            }
        });
    }
    public void show(View view2show){
        errormsgBg.setVisibility(View.GONE);
        listviewBg.setVisibility(View.GONE);
        progressingBg.setVisibility(View.GONE);
        view2show.setVisibility(View.VISIBLE);
    }
}
